package 栈;

import 链表.ListNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class No341扁平化嵌套列表迭代器 {

    /**
     * 题意:设计一个迭代器
     */

    public interface NestedInteger {

        //当前类是否为整形?是就getInteger,不是就去getList获取集合
        public boolean isInteger();

        public Integer getInteger();

        public List<NestedInteger> getList();

    }

    private static class Nest implements NestedInteger{

        private boolean flag;
        private Integer i;
        private List<NestedInteger> list;

        public Nest(Integer i) {
            this.flag=true;
            this.i = i;
        }

        public Nest(List<NestedInteger> list) {
            this.flag=false;
            this.list = list;
        }

        @Override
        public boolean isInteger() {
            return this.flag;
        }

        @Override
        public Integer getInteger() {
            return this.i;
        }

        @Override
        public List<NestedInteger> getList() {
            return this.list;
        }
    }

    static class NestedIterator implements Iterator<Integer> {

        List<Integer> list=new ArrayList<>();

        int index=0;

        public NestedIterator(List<NestedInteger> nestedList) {

            for (NestedInteger nestedInteger : nestedList) {
                if(nestedInteger.isInteger()){
                    list.add(nestedInteger.getInteger());
                }else{
                    dg(nestedInteger.getList());
                }
            }
        }

        private void dg(List<NestedInteger> nestedIntegers){

            for (NestedInteger nestedInteger : nestedIntegers) {
                if(nestedInteger.isInteger()){
                    list.add(nestedInteger.getInteger());
                }else{
                    dg(nestedInteger.getList());
                }
            }

        }

        @Override
        public Integer next() {
            return list.get(index++);

        }

        @Override
        public boolean hasNext() {
            return index!=list.size();
        }
    }

    public static void main(String[] args) {
        Nest nest1=new Nest(Arrays.asList(new Nest(1),new Nest(1)));
        Nest nest2=new Nest(2);
        Nest nest3=new Nest(Arrays.asList(new Nest(1),new Nest(1)));
        NestedIterator nestedIterator=new NestedIterator(Arrays.asList(nest1,nest2,nest3));
        while (nestedIterator.hasNext()){
            System.out.println(nestedIterator.next());
        }
    }

}
